package com.alander.nexusgo.im.netty;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * IM连接管理器
 */
public class ImConnectionManager {
    
    // 存储用户ID和通道的映射关系（用于单聊）
    private static final Map<Long, Channel> userChannels = new ConcurrentHashMap<>();
    
    // 存储群组ID和通道组的映射关系（用于群聊）
    private static final Map<Integer, ChannelGroup> chatRoomGroups = new ConcurrentHashMap<>();
    
    /**
     * 添加用户连接
     * @param userId 用户ID
     * @param channel 通道
     */
    public static void addUserChannel(long userId, Channel channel) {
        userChannels.put(userId, channel);
    }
    
    /**
     * 移除用户连接
     * @param userId 用户ID
     */
    public static void removeUserChannel(long userId) {
        userChannels.remove(userId);
    }
    
    /**
     * 获取用户通道
     * @param userId 用户ID
     * @return 通道
     */
    public static Channel getUserChannel(long userId) {
        return userChannels.get(userId);
    }
    
    /**
     * 添加群组成员
     * @param roomId 群组ID
     * @param channel 通道
     */
    public static void addChatRoomMember(int roomId, Channel channel) {
        chatRoomGroups.computeIfAbsent(roomId, k -> new DefaultChannelGroup(GlobalEventExecutor.INSTANCE))
                .add(channel);
    }
    
    /**
     * 移除群组成员
     * @param roomId 群组ID
     * @param channel 通道
     */
    public static void removeChatRoomMember(int roomId, Channel channel) {
        ChannelGroup group = chatRoomGroups.get(roomId);
        if (group != null) {
            group.remove(channel);
            // 如果群组为空，移除该群组
            if (group.isEmpty()) {
                chatRoomGroups.remove(roomId);
            }
        }
    }
    
    /**
     * 获取群组通道组
     * @param roomId 群组ID
     * @return 通道组
     */
    public static ChannelGroup getChatRoomGroup(int roomId) {
        return chatRoomGroups.get(roomId);
    }
    
    /**
     * 获取所有用户通道
     * @return 用户通道映射
     */
    public static Map<Long, Channel> getAllUserChannels() {
        return userChannels;
    }
}